package com.sskj.gocoinapp.presenter;

import com.google.gson.Gson;
import com.lzy.okgo.model.Response;
import com.sskj.common.base.HttpData;
import com.sskj.common.http.WebSocketObserver;
import com.sskj.gocoinapp.bean.PushTradeBean;
import com.sskj.gocoinapp.bean.TradeBean;
import com.sskj.gocoinapp.http.HttpConfig;
import com.sskj.gocoinapp.ui.fragment.TradeFragment;
import com.sskj.level.bean.SocketSendBean;
import com.sskj.lib.Constans;
import com.sskj.lib.http.JsonCallBack;

import java.util.List;

import io.reactivex.BackpressureStrategy;
import io.reactivex.disposables.Disposable;


public class TradeFragmentPresenter extends BasePresenter<TradeFragment> {

    private WebSocketObserver stockSocket;
    private Disposable stockDisposable;

    public void getData(String code) {
        httpService.getAllTrade(code)
                .execute(new JsonCallBack<HttpData<List<TradeBean>>>() {
                    @Override
                    public void onSuccess(Response<HttpData<List<TradeBean>>> response) {
                        HttpData<List<TradeBean>> httpData = response.body();
                        if (httpData.getStatus() == HttpConfig.OK) {
                            mView.updateUI(httpData.getData());

                        }
                    }
                });
    }

    public void initSocket(String code) {
        if (stockSocket == null) {
            stockSocket = httpService.pushCoinTrade(code);
            stockDisposable = stockSocket
                    .map(s -> new Gson().fromJson(s, PushTradeBean.class))
                    .subscribe(data -> mView.updateData(data), e -> {
                    });

        } else {
            stockSocket.send(new Gson().toJson(new SocketSendBean(Constans.NO_FIVE_PUSH)));
//            stockSocketFive.send(new Gson().toJson(new SocketSendBean(Constans.FIVE_PUSH)));
        }

    }

    public void sendCode(String code) {

        initSocket(code);
    }


    public void closeWebSocket() {
        stockSocket.close();
        stockSocket = null;
    }

}
